package cn.wowjoy.office.materialmanage.addReport;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.NewBaseActivity;
import cn.wowjoy.office.common.widget.keyborad.CustomBaseKeyboard;
import cn.wowjoy.office.common.widget.keyborad.CustomKeyboardManager;
import cn.wowjoy.office.common.widget.timepicker.TimePickerView;
import cn.wowjoy.office.data.response.RecordResponse;
import cn.wowjoy.office.databinding.ActivityEditStockBinding;
@Route(path = "/materialmanage/addreport/editstock")
public class EditStockActivity extends NewBaseActivity<ActivityEditStockBinding,AddStockViewModel> implements View.OnClickListener/*, View.OnFocusChangeListener*/ {



    @Autowired
    boolean isManualAdd;
    @Autowired
    RecordResponse record;
    @Autowired
    String goodsCode;
    @Autowired
    String headCode;

    private CustomKeyboardManager stockCustomKeyboardManager;
    private CustomKeyboardManager realStockcustomKeyboardManager;
    private CustomBaseKeyboard stockKeyboard;
    private CustomBaseKeyboard realStockKeyboard;


    private TimePickerView pvTime;
    @Override
    protected Class<AddStockViewModel> getViewModel() {
        return AddStockViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_edit_stock;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        ARouter.getInstance().inject(this);
        binding.setViewmodel(viewModel);
        initTimePicker();
        if (!isManualAdd && null != record){
            binding.indateEdit.setText(record.getIndate());
            binding.batchEdit.setText(record.getBatch());
            binding.stockEdit.setText(record.getStockCount());
            binding.realStockEdit.setText(record.getRealStockCount());

        } else {
            binding.indateEdit.setText(getCurrentTime());
            record = new RecordResponse();
            record.setCanDelete(true);
        }
//        binding.batchEdit.setOnFocusChangeListener(this);
        binding.batchEdit.addTextChangedListener(textWatcher2);
//        binding.stockEdit.addTextChangedListener(textWatcher);
//        binding.realStockEdit.addTextChangedListener(textWatcher1);
        binding.back.setOnClickListener(this);
        binding.addRecord.setOnClickListener(this);
        binding.indateRl.setOnClickListener(this);

        stockCustomKeyboardManager = new CustomKeyboardManager(this);
        realStockcustomKeyboardManager = new CustomKeyboardManager(this);
        stockKeyboard = new CustomBaseKeyboard(this, R.xml.stock_price_num_keyboard) {
            @Override
            public boolean handleSpecialKey(EditText etCurrent, int primaryCode) {
                return false;
            }
        };
        realStockKeyboard = new CustomBaseKeyboard(this, R.xml.stock_price_num_keyboard) {
            @Override
            public boolean handleSpecialKey(EditText etCurrent, int primaryCode) {
                return false;
            }
        };
        stockKeyboard.setOnTextChangeListener(new CustomBaseKeyboard.OnTextChangeListener() {
            @Override
            public void onChange(StringBuilder sb) {
                if (TextUtils.isEmpty(sb.toString().trim())){
                    binding.priceLimit.setSelected(false);
                    binding.priceLimit.setText("(0/16)");
                } else if (sb.toString().contains(".")){
                    if (sb.toString().trim().length() >= 17){
                        binding.priceLimit.setSelected(true);
                        binding.priceLimit.setText("(16/16)");
                    } else {
                        binding.priceLimit.setSelected(false);
                        binding.priceLimit.setText("("+ (sb.toString().trim().length() - 1) +"/16)");
                    }
                } else {
                    binding.priceLimit.setSelected(false);
                    binding.priceLimit.setText("("+ (sb.toString().trim().length()) +"/16)");
                }
            }
        });
        realStockKeyboard.setOnTextChangeListener(new CustomBaseKeyboard.OnTextChangeListener() {
            @Override
            public void onChange(StringBuilder sb) {
                if (TextUtils.isEmpty(sb.toString().trim())){
                    binding.realStockLimit.setSelected(false);
                    binding.realStockLimit.setText("(0/16)");
                } else if (sb.toString().contains(".")){
                    if (sb.toString().contains("-")){
                        if (sb.toString().trim().length() >= 18){
                            binding.realStockLimit.setSelected(true);
                            binding.realStockLimit.setText("(16/16)");
                        } else {
                            binding.realStockLimit.setSelected(false);
                            binding.realStockLimit.setText("("+ (sb.toString().trim().length() - 2) +"/16)");
                        }
                    } else {
                        if (sb.toString().trim().length() >= 17){
                            binding.realStockLimit.setSelected(true);
                            binding.realStockLimit.setText("(16/16)");
                        } else {
                            binding.realStockLimit.setSelected(false);
                            binding.realStockLimit.setText("("+ (sb.toString().trim().length() - 1) +"/16)");
                        }
                    }

                } else if (sb.toString().contains("-")){
                    if (sb.toString().trim().length() >= 17){
                        binding.realStockLimit.setSelected(true);
                        binding.realStockLimit.setText("(16/16)");
                    } else {
                        binding.realStockLimit.setSelected(false);
                        binding.realStockLimit.setText("("+ (sb.toString().trim().length() - 1) +"/16)");
                    }
                } else {
                    binding.realStockLimit.setSelected(false);
                    binding.realStockLimit.setText("("+ (sb.toString().trim().length()) +"/16)");
                }
            }
        });
        stockCustomKeyboardManager.setShowUnderView(binding.tempRl);
        realStockcustomKeyboardManager.setShowUnderView(binding.tempRl);
        stockCustomKeyboardManager.attachTo(binding.priceEdit, stockKeyboard);
        realStockcustomKeyboardManager.attachTo(binding.realStockEdit, realStockKeyboard);
        binding.priceEdit.setOnClickListener(this);
        binding.realStockEdit.setOnClickListener(this);

    }
    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }


    private void initTimePicker(){
        //控制时间范围(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
        //因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        startDate.set(2000, 0, 1);
        Calendar endDate = Calendar.getInstance();
        endDate.set(3000, 11, 31);
        //时间选择器
        pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                // 这里回调过来的v,就是show()方法里面所添加的 View 参数，如果show的时候没有添加参数，v则为null
                /*btn_Time.setText(getTime(date));*/
                binding.indateEdit.setText(getTime(date));
                Calendar cal=Calendar.getInstance();
                cal.setTime(date);
                pvTime.setDate(cal);

            }
        })
                //年月日时分秒 的显示与否，不设置则默认全部显示
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("年", "月", "日", "", "", "")
                .isCenterLabel(true)
                .isCyclic(true)
                .setDividerColor(0xFFDCDCDC)
                .setContentSize(13)
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setTextColorCenter(0xFF369FF1)
                .setTextColorOut(0xFF666666)
//                .setBackgroundId(0x00FFFFFF) //设置外部遮罩颜色
                .setDecorView(null)
                .build();

    }
    private String getCurrentTime(){
        SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        return str;
    }
//    private TextWatcher textWatcher = new TextWatcher() {
//
//        @Override
//        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//        }
//
//        @Override
//        public void onTextChanged(CharSequence s, int start, int before, int count) {
//            // 限制最多能输入9位整数
//            if (s.toString().contains(".")) {
//                if (s.toString().indexOf(".") > 14) {
//                    s = s.toString().subSequence(0,14) + s.toString().substring(s.toString().indexOf("."));
//                    binding.stockEdit.setText(s);
////                    binding.stockEdit.setSelection(s.length());
//                }
//            }else {
//                if (s.toString().length() > 14){
//                    s = s.toString().subSequence(0,14);
//                    binding.stockEdit.setText(s);
////                    binding.stockEdit.setSelection(14);
//                }
//            }
//            // 判断小数点后只能输入两位
//            if (s.toString().contains(".")) {
//                if (s.length() - 1 - s.toString().indexOf(".") > 2) {
//                    s = s.toString().subSequence(0,
//                            s.toString().indexOf(".") + 3);
//                    binding.stockEdit.setText(s);
////                    binding.stockEdit.setSelection(s.length());
//                }
//            }
//            //如果第一个数字为0，第二个不为点，就不允许输入
//            if (s.toString().startsWith("0") && s.toString().trim().length() > 1) {
//                if (!s.toString().substring(1, 2).equals(".")) {
//                    binding.stockEdit.setText(s.subSequence(0, 1));
//                    binding.stockEdit.setSelection(1);
//                    return;
//                }
//            }
//
////            如果"."在起始位置,则起始位置自动补0
//            if (s.toString().trim().substring(0).equals(".")) {
//                s = "0" + s ;
//                binding.stockEdit.setText(s);
//                binding.stockEdit.setSelection(2);
//            }
//
//            if (TextUtils.isEmpty(s)){
//                binding.stockLimit.setSelected(false);
//                binding.stockLimit.setText("(0/16)");
//            } else if (s.toString().contains(".")){
//                if (s.toString().trim().length() >= 17){
//                    binding.stockLimit.setSelected(true);
//                    binding.stockLimit.setText("(16/16)");
//                } else {
//                    binding.stockLimit.setSelected(false);
//                    binding.stockLimit.setText("("+ (s.toString().trim().length() - 1) +"/16)");
//                }
//            } else {
//                binding.stockLimit.setSelected(false);
//                binding.stockLimit.setText("("+ (s.toString().trim().length()) +"/16)");
//            }
//
//        }
//
//        @Override
//        public void afterTextChanged(Editable s) {
////            // 这里可以知道你已经输入的字数，大家可以自己根据需求来自定义文本控件实时的显示已经输入的字符个数
//            int after_length = s.length();// 输入内容后编辑框所有内容的总长度
//
//
//
//
//        }
//    };
//    private TextWatcher textWatcher1 = new TextWatcher() {
//
//        @Override
//        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//        }
//
//        @Override
//        public void onTextChanged(CharSequence s, int start, int before, int count) {
//            // 限制最多能输入9位整数
//            if (s.toString().contains(".")) {
//                if (s.toString().indexOf(".") > 14) {
//                    s = s.toString().subSequence(0,14) + s.toString().substring(s.toString().indexOf("."));
//                    binding.realStockEdit.setText(s);
//                    binding.realStockEdit.setSelection(s.length());
//                }
//            }else {
//                if (s.toString().length() > 14){
//                    s = s.toString().subSequence(0,14);
//                    binding.realStockEdit.setText(s);
//                    binding.realStockEdit.setSelection(14);
//                }
//            }
//            // 判断小数点后只能输入两位
//            if (s.toString().contains(".")) {
//                if (s.length() - 1 - s.toString().indexOf(".") > 2) {
//                    s = s.toString().subSequence(0,
//                            s.toString().indexOf(".") + 3);
//                    binding.realStockEdit.setText(s);
//                    binding.realStockEdit.setSelection(s.length());
//                }
//            }
//            //如果第一个数字为0，第二个不为点，就不允许输入
//            if (s.toString().startsWith("0") && s.toString().trim().length() > 1) {
//                if (!s.toString().substring(1, 2).equals(".")) {
//                    binding.realStockEdit.setText(s.subSequence(0, 1));
//                    binding.realStockEdit.setSelection(1);
//                    return;
//                }
//            }
//
////            如果"."在起始位置,则起始位置自动补0
//            if (s.toString().trim().substring(0).equals(".")) {
//                s = "0" + s ;
//                binding.realStockEdit.setText(s);
//                binding.realStockEdit.setSelection(2);
//            }
//
//            if (TextUtils.isEmpty(s)){
//                binding.realStockLimit.setSelected(false);
//                binding.realStockLimit.setText("(0/16)");
//            } else if (s.toString().contains(".")){
//                if (s.toString().trim().length() >= 17){
//                    binding.realStockLimit.setSelected(true);
//                    binding.realStockLimit.setText("(16/16)");
//                } else {
//                    binding.realStockLimit.setSelected(false);
//                    binding.realStockLimit.setText("("+ (s.toString().trim().length() - 1) +"/16)");
//                }
//            } else {
//                binding.realStockLimit.setSelected(false);
//                binding.realStockLimit.setText("("+ (s.toString().trim().length()) +"/16)");
//            }
//
//        }
//
//        @Override
//        public void afterTextChanged(Editable s) {
////            // 这里可以知道你已经输入的字数，大家可以自己根据需求来自定义文本控件实时的显示已经输入的字符个数
//            int after_length = s.length();// 输入内容后编辑框所有内容的总长度
//
//
//
//
//        }
//    };
    private TextWatcher textWatcher2 = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // 限制最多能输入9位整数

            if (s.toString().length() > 50) {
                s = s.toString().subSequence(0,50);
                binding.batchEdit.setText(s);
                binding.batchEdit.setSelection(s.length());
            }


            if (TextUtils.isEmpty(s)){
                binding.batchLimit.setSelected(false);
                binding.batchLimit.setText("(0/50)");
            } else if (s.toString().trim().length() >= 50){
                binding.batchLimit.setSelected(true);
                binding.batchLimit.setText("(50/50)");
            } else {
                binding.batchLimit.setSelected(false);
                binding.batchLimit.setText("("+ (s.toString().trim().length()) +"/50)");
            }

        }

        @Override
        public void afterTextChanged(Editable s) {
//            // 这里可以知道你已经输入的字数，大家可以自己根据需求来自定义文本控件实时的显示已经输入的字符个数
            int after_length = s.length();// 输入内容后编辑框所有内容的总长度




        }
    };

    private boolean isInvaild(){
        if (TextUtils.isEmpty(binding.realStockEdit.getText().toString().trim())){
            Toast.makeText(this, "实际库存不能为空哦~~", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (TextUtils.isEmpty(binding.priceEdit.getText().toString().trim())){
            Toast.makeText(this, "单价不能为空哦~~", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (!TextUtils.isEmpty(binding.priceEdit.getText().toString().trim()) && !TextUtils.isEmpty(binding.realStockEdit.getText().toString().trim()))
            return true;
        Toast.makeText(this, "请确保信息填写完整哦~", Toast.LENGTH_SHORT).show();
        return false;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back:
                onBackPressed();
                break;
            case R.id.add_record:
                if (isInvaild()){
                    Intent intent = new Intent();
                    String time = binding.indateEdit.getText().toString().trim().replace("-","/");
                    record.setBatch(binding.batchEdit.getText().toString().trim());
                    record.setIndate(time);
                    record.setStockCount(binding.stockEdit.getText().toString().trim());
                    record.setRealStockCount(binding.realStockEdit.getText().toString().trim());
                    record.setPrice(binding.priceEdit.getText().toString().trim());
                    record.setHeadCode(headCode);
                    record.setGoodsCode(goodsCode);
                    intent.putExtra("record",record);
                    setResult(RESULT_OK,intent);
                    finish();
                }
                break;
            case R.id.indate_rl:
                hideSoftInput();
                if (null != pvTime)
                    pvTime.show();
                break;
            case R.id.price_edit:
                hideSoftInput();
                binding.batchEdit.clearFocus();
                stockCustomKeyboardManager.focus();
                break;
            case R.id.real_stock_edit:
                hideSoftInput();
                binding.batchEdit.clearFocus();
                realStockcustomKeyboardManager.focus();
                break;
        }

    }

//    @Override
//    public void onFocusChange(View v, boolean hasFocus) {
//        Toast.makeText(this, "batchEdit has focus:::::::::::::::"+hasFocus , Toast.LENGTH_SHORT).show();
//    }
}
